package com.swanclouds.redfish.chassis;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.swanclouds.api.Apis;
import com.swanclouds.api.chassis.NetworkAdaptersService;
import com.swanclouds.api.chassis.NetworkPortsService;
import com.swanclouds.core.transport.ClientConstants;
import com.swanclouds.redfish.chassis.domain.NetworkAdaptersModel;
import com.swanclouds.redfish.chassis.domain.NetworkPortsModel;
import com.swanclouds.redfish.internal.BaseChassisService;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: HuangFuYuHui
 * Title: NetworkPortsServiceImpl
 * Description: TODO
 * Date: 2022/7/22 15:33
 */
public class NetworkPortsServiceImpl extends BaseChassisService implements NetworkPortsService {

    private NetworkAdaptersService networkAdaptersService = new NetworkAdaptersServiceImpl();

    /**
     * 查询指定网络端口集合资源信息
     * @param networkAdapterId 网络适配器Id
     * @param networkPortId 网络端口Id
     * @return com.swanclouds.model.chassis.NetworkPorts
     **/
    @Override
    public NetworkPortsModel get(String networkAdapterId, String networkPortId) {
        Preconditions.checkNotNull(networkAdapterId, "networkAdaptersId is null");
        Preconditions.checkNotNull(networkPortId, "networkPortsId is null");
        return get(NetworkPortsModel.class,uri(ClientConstants.PATH_CHASSIS_NETWORKPORTS_ID,getChassisId(),networkAdapterId,networkPortId)).execute();
    }

    /**
     * 查询指定网络适配器的网络端口集合资源信息
     *
     * @param networkAdapterId 网络适配器Id
     * @return List
     */
    @Override
    public List<NetworkPortsModel> list(String networkAdapterId) {
        List<NetworkPortsModel> list = Lists.newArrayList();
        NetworkAdaptersModel networkAdapter = Apis.Chassis().Detail().NetworkAdapters().getNetworkAdapter(networkAdapterId);
        networkAdapter.getControllers().stream().forEach(controller -> {
            controller.getLink().getNetworkPorts().stream().forEach(ref -> {
                list.add(get(NetworkPortsModel.class, uri(ref)).execute());
            });
        });
        return list;
    }

    /**
     * 查询网络端口集合资源信息
     * @return java.util.List
     **/
    @Override
    public List<NetworkPortsModel> listAll() {
        List<NetworkPortsModel> networkPortsModels = new ArrayList<NetworkPortsModel>();
        List<NetworkAdaptersModel> list = networkAdaptersService.list();
        for (NetworkAdaptersModel networkAdaptersModel : list) {
            List<NetworkAdaptersModel.Controller> controllers = networkAdaptersModel.getControllers();
            for (NetworkAdaptersModel.Controller controller : controllers) {
                controller.getLink().getNetworkPorts().stream().forEach(ref->{
                    NetworkPortsModel execute = get(NetworkPortsModel.class, uri(ref)).execute();
                    networkPortsModels.add(execute);
                });
            }
        }
        return networkPortsModels;
    }

}
